from datetime import timedelta

from flask_restful import Resource
from sqlalchemy import and_, not_

from .system_utils import *
from ..models import *


class BaseResource(Resource):
    decorators = [admin_login_required]


##################系统监控缓存
class SysMonitorCache(BaseResource):
    def get(self):
        res_dict = {"msg": "操作成功", "code": 200, "data": {
            "commandStats": [{"name": "set", "value": "90"}, {"name": "keys", "value": "1"},
                             {"name": "setex", "value": "97"}, {"name": "del", "value": "26"},
                             {"name": "info", "value": "3"}, {"name": "dbsize", "value": "1"},
                             {"name": "get", "value": "227361"}],
            "info": {"used_memory_dataset_perc": "72.03%", "aof_current_rewrite_time_sec": "-1",
                     "used_memory_peak_perc": "85.40%", "rss_overhead_ratio": "2.59",
                     "db0": "keys=17,expires=1,avg_ttl=83142400", "active_defrag_hits": "0",
                     "atomicvar_api": "c11-builtin", "rss_overhead_bytes": "5795840", "gcc_version": "7.3.1",
                     "keyspace_misses": "224222", "redis_git_dirty": "0", "connected_clients": "1",
                     "master_repl_offset": "0", "repl_backlog_active": "0", "rdb_changes_since_last_save": "0",
                     "client_recent_max_output_buffer": "0", "rejected_connections": "0", "io_threads_active": "0",
                     "unexpected_error_replies": "0", "run_id": "7404875b25142cc4f753319b22c4fd220edf2bbf",
                     "maxmemory": "0", "mem_allocator": "jemalloc-5.1.0", "used_cpu_sys": "1198.213349",
                     "expired_stale_perc": "0.00", "blocked_clients": "0", "total_commands_processed": "227578",
                     "sync_partial_err": "0", "current_save_keys_total": "0", "total_connections_received": "32",
                     "evicted_keys": "0", "maxmemory_policy": "noeviction", "used_cpu_sys_main_thread": "1192.289559",
                     "config_file": "/www/server/redis/redis.conf", "used_memory_human": "866.05K",
                     "allocator_rss_ratio": "2.85", "role": "master", "connected_slaves": "0",
                     "process_supervised": "no", "aof_last_cow_size": "0", "used_memory_rss_human": "9.01M",
                     "cluster_enabled": "0", "allocator_rss_bytes": "2367488", "mem_fragmentation_ratio": "11.19",
                     "used_memory_scripts": "0", "repl_backlog_size": "1048576", "uptime_in_days": "34",
                     "used_memory_peak": "1038480", "number_of_cached_scripts": "0",
                     "mem_fragmentation_bytes": "8601296", "used_memory_startup": "809976",
                     "total_system_memory_human": "3.70G", "hz": "10", "used_memory_lua_human": "37.00K",
                     "instantaneous_input_kbps": "0.00", "used_memory_scripts_human": "0B",
                     "rdb_bgsave_in_progress": "0", "total_net_output_bytes": "1872654", "uptime_in_seconds": "2984793",
                     "mem_clients_normal": "20504", "total_forks": "41", "slave_expires_tracked_keys": "0",
                     "current_fork_perc": "0.00", "master_replid2": "0000000000000000000000000000000000000000",
                     "total_net_input_bytes": "9938663", "instantaneous_output_kbps": "0.00", "expired_keys": "68",
                     "allocator_frag_ratio": "1.33", "aof_last_write_status": "ok", "redis_version": "6.2.4",
                     "allocator_frag_bytes": "318576", "maxmemory_human": "0B", "rdb_last_save_time": "1647268211",
                     "lazyfree_pending_objects": "0", "aof_rewrite_scheduled": "0", "migrate_cached_sockets": "0",
                     "keyspace_hits": "3139", "allocator_allocated": "963472", "used_memory": "886840",
                     "mem_replication_backlog": "0", "used_memory_dataset": "55368", "pubsub_patterns": "0",
                     "used_cpu_user_children": "0.023662", "master_replid": "eaf2534d3629d7f8f4b0cc74ca73eb754eee5179",
                     "mem_aof_buffer": "0", "total_error_replies": "0", "rdb_last_bgsave_status": "ok",
                     "redis_mode": "standalone", "total_writes_processed": "227575", "allocator_resident": "3649536",
                     "allocator_active": "1282048", "current_cow_size_age": "0", "current_save_keys_processed": "0",
                     "expired_time_cap_reached_count": "0", "sync_full": "0", "rdb_current_bgsave_time_sec": "-1",
                     "aof_rewrite_in_progress": "0", "multiplexing_api": "epoll", "module_fork_in_progress": "0",
                     "tracking_clients": "0", "rdb_last_cow_size": "483328", "mem_not_counted_for_evict": "0",
                     "dump_payload_sanitizations": "0", "redis_git_sha1": "00000000", "tracking_total_keys": "0",
                     "maxclients": "10000", "clients_in_timeout_table": "0", "latest_fork_usec": "332",
                     "rdb_last_bgsave_time_sec": "0", "os": "Linux 3.10.0-1160.24.1.el7.x86_64 x86_64",
                     "used_cpu_sys_children": "0.050616", "sync_partial_ok": "0", "module_fork_last_cow_size": "0",
                     "arch_bits": "64", "used_memory_lua": "37888", "mem_clients_slaves": "0",
                     "tracking_total_items": "0", "used_cpu_user_main_thread": "1816.356566", "lazyfreed_objects": "0",
                     "process_id": "2872", "tracking_total_prefixes": "0", "total_system_memory": "3972907008",
                     "master_failover_state": "no-failover", "repl_backlog_histlen": "0",
                     "executable": "/www/server/redis/src/redis-server", "used_memory_rss": "9445376", "loading": "0",
                     "active_defrag_running": "0", "used_memory_peak_human": "1014.14K", "aof_enabled": "0",
                     "io_threaded_reads_processed": "0", "total_reads_processed": "227607", "second_repl_offset": "-1",
                     "active_defrag_misses": "0", "configured_hz": "10", "active_defrag_key_hits": "0",
                     "used_cpu_user": "1820.546777", "io_threaded_writes_processed": "0",
                     "redis_build_id": "22aabf1c682f653", "cluster_connections": "0", "aof_last_bgrewrite_status": "ok",
                     "client_recent_max_input_buffer": "24", "active_defrag_key_misses": "0",
                     "instantaneous_ops_per_sec": "0", "repl_backlog_first_byte_offset": "0",
                     "expire_cycle_cpu_milliseconds": "43707", "current_cow_size": "0", "tcp_port": "6379",
                     "pubsub_channels": "0", "server_time_usec": "1647270601253781", "lru_clock": "3103433",
                     "aof_last_rewrite_time_sec": "-1", "used_memory_overhead": "831472"}, "dbSize": 17}}
        return res_dict


##################系统监控服务监控


class SysMonitorServer(BaseResource):
    def get(self):
        res_dict = {"msg": "操作成功", "code": 200,
                    "data": {
                        "cpu": {"cpuNum": 2, "total": 199000.0, "sys": 0.0, "used": 0.5, "wait": 0.0, "free": 99.5},
                        "mem": {"total": 3.7, "used": 2.03, "free": 1.67, "usage": 54.97},
                        "jvm": {"total": 134.5, "max": 843.0, "free": 58.95, "version": "1.8.0_121",
                                "home": "/usr/java/jdk1.8.0_121/jre", "startTime": "2022-02-19 11:27:29",
                                "usage": 56.17,
                                "used": 75.55, "runTime": "23天11小时38分钟", "name": "Java HotSpot(TM) 64-Bit Server VM"},
                        "sys": {"computerName": "huawei-node01", "computerIp": "127.0.0.1", "userDir": "/",
                                "osName": "Linux",
                                "osArch": "amd64"}, "sysFiles": [
                            {"dirName": "/", "sysTypeName": "ext4", "typeName": "/", "total": "39.2 GB",
                             "free": "13.2 GB",
                             "used": "26.1 GB", "usage": 66.47}]}}
        # res_dict = {
        #     "code": 200,
        #     "msg": "操作成功",
        # }
        return res_dict


##################日志管理登录日志
class SysLogininForResource(BaseResource):

    def get(self, id=None):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        if id:
            role_dict = SysLogininfor.query.get(id).to_dict()
            res_dict["data"] = response_camel_case_dict(role_dict)
        else:
            params_dict = request.args
            page_num = int(params_dict.get("pageNum", 1))
            page_size = int(params_dict.get("pageSize", 10))
            qs = SysLogininfor.query.filter()

            pa = qs.order_by(SysLogininfor.login_time.asc()).paginate(page_num, page_size, False)
            rows_data = [response_camel_case_dict(item.to_dict()) for item in pa.items]
            res_dict["rows"] = rows_data
            res_dict["total"] = pa.total
        return res_dict

    def post(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)

        sys_role_dict = {
            "role_name": params_dict.get("role_name"),
            "role_key": params_dict.get("role_key"),
            "role_sort": params_dict.get("role_sort"),
            "data_scope": params_dict.get("data_scope"),
            "menu_check_strictly": "1" if params_dict.get("menu_check_strictly") else "0",
            "dept_check_strictly": "1" if params_dict.get("dept_check_strictly") else "0",
            "remark": params_dict.get("remark"),
        }

        new_object = SysRole(**sys_role_dict)
        db.session.add(new_object)
        db.session.commit()

        new_role_id = new_object.role_id
        new_menu_ids = params_dict.get("menu_ids")
        update_menu_by_role_id(role_id=new_role_id, new_menu_ids=new_menu_ids)
        db.session.commit()
        res_dict["msg"] = str(new_role_id) + "添加成功"
        return res_dict

    def put(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        role_id = params_dict.get("role_id")
        menu_ids = params_dict.get("menu_ids")
        params_dict["menu_check_strictly"] = "1" if params_dict.get("menu_check_strictly") else "0"
        params_dict["dept_check_strictly"] = "1" if params_dict.get("dept_check_strictly") else "0"
        update_fields = [
            "role_name",
            "role_key",
            "role_sort",
            "data_scope",
            "menu_check_strictly",
            "dept_check_strictly",
            "remark",
            "status",
        ]
        old_object = SysRole.query.get(role_id)
        for item_k, item_v in params_dict.items():
            if item_k in update_fields:
                if getattr(old_object, item_k) != item_v:
                    setattr(old_object, item_k, item_v)
        db.session.commit()
        # 更新当前角色的菜单列表
        update_menu_by_role_id(role_id, menu_ids)
        return res_dict

    def delete(self, id):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        id_list = [int(item) for item in id.split(",")]
        del_objects = SysRole.query.filter(SysRole.role_id.in_(id_list))
        res = SysUserRole.query.filter(SysUserRole.role_id.in_(id_list)).all()
        if res:
            res_dict["code"] = 500
            res_dict["msg"] = id + "已分配用户,不能删除"
            return res_dict
        for item in del_objects:
            db.session.delete(item)
        del_role_menu_objects = SysRoleMenu.query.filter(SysRoleMenu.role_id.in_(id_list)).all()
        for item in del_role_menu_objects:
            db.session.delete(item)
        del_role_dept_objects = SysRoleDept.query.filter(SysRoleDept.role_id.in_(id_list)).all()
        for item in del_role_dept_objects:
            db.session.delete(item)

        db.session.commit()
        return res_dict


##################日志管理操作日志
class SysOperlogResource(BaseResource):

    def get(self, id=None):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        if id:
            role_dict = SysOperLog.query.get(id).to_dict()
            res_dict["data"] = response_camel_case_dict(role_dict)
        else:
            params_dict = request.args
            page_num = int(params_dict.get("pageNum", 1))
            page_size = int(params_dict.get("pageSize", 10))
            qs = SysOperLog.query.filter()

            pa = qs.order_by(SysOperLog.oper_time.asc()).paginate(page_num, page_size, False)
            rows_data = [response_camel_case_dict(item.to_dict()) for item in pa.items]
            res_dict["rows"] = rows_data
            res_dict["total"] = pa.total
        return res_dict

    def post(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)

        sys_role_dict = {
            "role_name": params_dict.get("role_name"),
            "role_key": params_dict.get("role_key"),
            "role_sort": params_dict.get("role_sort"),
            "data_scope": params_dict.get("data_scope"),
            "menu_check_strictly": "1" if params_dict.get("menu_check_strictly") else "0",
            "dept_check_strictly": "1" if params_dict.get("dept_check_strictly") else "0",
            "remark": params_dict.get("remark"),
        }

        new_object = SysRole(**sys_role_dict)
        db.session.add(new_object)
        db.session.commit()

        new_role_id = new_object.role_id
        new_menu_ids = params_dict.get("menu_ids")
        update_menu_by_role_id(role_id=new_role_id, new_menu_ids=new_menu_ids)
        db.session.commit()
        res_dict["msg"] = str(new_role_id) + "添加成功"
        return res_dict

    def put(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        role_id = params_dict.get("role_id")
        menu_ids = params_dict.get("menu_ids")
        params_dict["menu_check_strictly"] = "1" if params_dict.get("menu_check_strictly") else "0"
        params_dict["dept_check_strictly"] = "1" if params_dict.get("dept_check_strictly") else "0"
        update_fields = [
            "role_name",
            "role_key",
            "role_sort",
            "data_scope",
            "menu_check_strictly",
            "dept_check_strictly",
            "remark",
            "status",
        ]
        old_object = SysRole.query.get(role_id)
        for item_k, item_v in params_dict.items():
            if item_k in update_fields:
                if getattr(old_object, item_k) != item_v:
                    setattr(old_object, item_k, item_v)
        db.session.commit()
        # 更新当前角色的菜单列表
        update_menu_by_role_id(role_id, menu_ids)
        return res_dict

    def delete(self, id):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        id_list = [int(item) for item in id.split(",")]
        del_objects = SysRole.query.filter(SysRole.role_id.in_(id_list))
        res = SysUserRole.query.filter(SysUserRole.role_id.in_(id_list)).all()
        if res:
            res_dict["code"] = 500
            res_dict["msg"] = id + "已分配用户,不能删除"
            return res_dict
        for item in del_objects:
            db.session.delete(item)
        del_role_menu_objects = SysRoleMenu.query.filter(SysRoleMenu.role_id.in_(id_list)).all()
        for item in del_role_menu_objects:
            db.session.delete(item)
        del_role_dept_objects = SysRoleDept.query.filter(SysRoleDept.role_id.in_(id_list)).all()
        for item in del_role_dept_objects:
            db.session.delete(item)

        db.session.commit()
        return res_dict


##################通知公告
class SysNoticeResource(BaseResource):

    def get(self, id=None):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        if id:
            role_dict = SysNotice.query.get(id).to_dict()
            res_dict["data"] = response_camel_case_dict(role_dict)
        else:
            params_dict = request.args
            page_num = int(params_dict.get("pageNum", 1))
            page_size = int(params_dict.get("pageSize", 10))
            qs = SysNotice.query.filter()

            pa = qs.order_by(SysNotice.create_time.asc()).paginate(page_num, page_size, False)
            rows_data = [response_camel_case_dict(item.to_dict()) for item in pa.items]
            res_dict["rows"] = rows_data
            res_dict["total"] = pa.total
        return res_dict

    def post(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)

        sys_role_dict = {
            "role_name": params_dict.get("role_name"),
            "role_key": params_dict.get("role_key"),
            "role_sort": params_dict.get("role_sort"),
            "data_scope": params_dict.get("data_scope"),
            "menu_check_strictly": "1" if params_dict.get("menu_check_strictly") else "0",
            "dept_check_strictly": "1" if params_dict.get("dept_check_strictly") else "0",
            "remark": params_dict.get("remark"),
        }

        new_object = SysRole(**sys_role_dict)
        db.session.add(new_object)
        db.session.commit()

        new_role_id = new_object.role_id
        new_menu_ids = params_dict.get("menu_ids")
        update_menu_by_role_id(role_id=new_role_id, new_menu_ids=new_menu_ids)
        db.session.commit()
        res_dict["msg"] = str(new_role_id) + "添加成功"
        return res_dict

    def put(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        role_id = params_dict.get("role_id")
        menu_ids = params_dict.get("menu_ids")
        params_dict["menu_check_strictly"] = "1" if params_dict.get("menu_check_strictly") else "0"
        params_dict["dept_check_strictly"] = "1" if params_dict.get("dept_check_strictly") else "0"
        update_fields = [
            "role_name",
            "role_key",
            "role_sort",
            "data_scope",
            "menu_check_strictly",
            "dept_check_strictly",
            "remark",
            "status",
        ]
        old_object = SysRole.query.get(role_id)
        for item_k, item_v in params_dict.items():
            if item_k in update_fields:
                if getattr(old_object, item_k) != item_v:
                    setattr(old_object, item_k, item_v)
        db.session.commit()
        # 更新当前角色的菜单列表
        update_menu_by_role_id(role_id, menu_ids)
        return res_dict

    def delete(self, id):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        id_list = [int(item) for item in id.split(",")]
        del_objects = SysRole.query.filter(SysRole.role_id.in_(id_list))
        res = SysUserRole.query.filter(SysUserRole.role_id.in_(id_list)).all()
        if res:
            res_dict["code"] = 500
            res_dict["msg"] = id + "已分配用户,不能删除"
            return res_dict
        for item in del_objects:
            db.session.delete(item)
        del_role_menu_objects = SysRoleMenu.query.filter(SysRoleMenu.role_id.in_(id_list)).all()
        for item in del_role_menu_objects:
            db.session.delete(item)
        del_role_dept_objects = SysRoleDept.query.filter(SysRoleDept.role_id.in_(id_list)).all()
        for item in del_role_dept_objects:
            db.session.delete(item)

        db.session.commit()
        return res_dict


##################参数设置

class InitPasswordResource(BaseResource):

    def get(self, key):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        t_res_object = SysConfig.query.filter(SysConfig.config_key == key).first()
        if t_res_object:
            res_dict["data"] = t_res_object.to_dict()
        return res_dict


class SysConfigResource(BaseResource):

    def get(self, id=None):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        if id:
            print(id)
            res_dict["data"] = response_camel_case_dict(SysConfig.query.get(id).to_dict())
        else:
            params_dict = request.args
            params_dict = request_snake_case_dict(params_dict)

            page_num = int(params_dict.get("page_num", 1))
            page_size = int(params_dict.get("page_size", 10))
            config_name = params_dict.get("config_name")
            config_key = params_dict.get("config_key")
            config_type = params_dict.get("config_type")

            filter_args = and_(
                SysConfig.config_name == config_name if config_name else True,
                SysConfig.config_key == config_key if config_key else True,
                SysConfig.config_type == config_type if config_type else True,
            )
            base_query = SysConfig.query.filter(filter_args)

            begin_time = params_dict.get("params[beginTime]")
            end_time = params_dict.get("params[endTime]")

            if all([begin_time, end_time]):
                begin_date = datetime.strptime(begin_time, "%Y-%m-%d")
                end_date = datetime.strptime(end_time, "%Y-%m-%d") + timedelta(days=1)
                base_query = base_query.filter(
                    and_(SysConfig.create_time >= begin_date, SysConfig.create_time <= end_date))

            pa = base_query.order_by(SysConfig.create_time.asc()).paginate(page_num, page_size, False)
            rows_data = [response_camel_case_dict(item.to_dict()) for item in pa.items]
            res_dict["rows"] = rows_data
            res_dict["total"] = pa.total
        return res_dict

    def post(self):
        res_dict = {
            "code": 200,
            "msg": "添加成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        return res_dict

    def put(self):
        res_dict = {
            "code": 200,
            "msg": "修改成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)

        return res_dict

    def delete(self, id):
        ids_list = id.split(",")
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        return res_dict


##################字典管理

class SysDictDatumResource(BaseResource):
    def get(self, id=None):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        if id:
            res_object = SysDictDatum.query.get(id)
            res_dict["data"] = response_camel_case_dict(res_object.to_dict())
            return res_dict
        else:
            params_dict = request.args
            params_dict = request_snake_case_dict(params_dict)
            page_num = int(params_dict.get("page_num", 1))
            page_size = int(params_dict.get("page_size", 10))
            dict_type = params_dict.get("dict_type")
            dict_label = params_dict.get("dict_label")
            status = params_dict.get("status")

            base_query = SysDictDatum.query.filter()
            filter_args = and_(
                SysDictDatum.dict_type == dict_type if dict_type else True,
                SysDictDatum.dict_label == dict_label if dict_label else True,
                SysDictDatum.status == status if status else True,
            )

            base_query = base_query.filter(filter_args)

            pa = base_query.order_by(SysDictDatum.dict_sort.asc()).paginate(page_num, page_size, False)
            rows_list = [response_camel_case_dict(item.to_dict()) for item in pa.items]
            res_dict["rows"] = rows_list
            res_dict["total"] = pa.total
            return res_dict

    def post(self):
        res_dict = {
            "code": 200,
            "msg": "添加成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        temp_object = SysDictDatum(**params_dict)
        save_objects([temp_object])
        return res_dict

    def put(self):
        res_dict = {
            "code": 200,
            "msg": "修改成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        dict_code = params_dict.get("dict_code")
        old_object = SysDictDatum.query.get(dict_code)
        update_fields = [
            "dict_sort",
            "dict_label",
            "dict_value",
            "dict_type",
            "css_class",
            "status",
            "remark",
        ]

        for item_k in update_fields:
            item_v = params_dict.get(item_k)
            if getattr(old_object, item_k) != item_v:
                setattr(old_object, item_k, item_v)
        update_objects([old_object])
        return res_dict

    def delete(self, id):
        ids_list = id.split(",")
        SysDictDatum.query.filter(SysDictDatum.dict_code.in_(ids_list)).delete()
        db.session.commit()
        res_dict = {
            "code": 200,
            "msg": "删除成功",
        }
        return res_dict


class SysDictRefreshCache(BaseResource):

    def delete(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        return res_dict


class SysDictResource(BaseResource):

    def get(self, id=None):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        if id:
            role_dict = SysDictType.query.get(id).to_dict()
            res_dict["data"] = response_camel_case_dict(role_dict)
        else:
            params_dict = request.args
            page_num = int(params_dict.get("pageNum", 1))
            page_size = int(params_dict.get("pageSize", 10))
            base_query = SysDictType.query.filter()
            base_query = base_query.filter_by(dict_name=params_dict.get("dict_name")) if params_dict.get(
                "dict_name") else base_query
            base_query = base_query.filter_by(dict_type=params_dict.get("dict_type")) if params_dict.get(
                "dict_type") else base_query
            base_query = base_query.filter_by(status=params_dict.get("status")) if params_dict.get(
                "status") else base_query

            begin_time = params_dict.get("params[beginTime]")
            end_time = params_dict.get("params[endTime]")

            if all([begin_time, end_time]):
                begin_date = datetime.strptime(begin_time, "%Y-%m-%d")
                end_date = datetime.strptime(end_time, "%Y-%m-%d") + timedelta(days=1)
                base_query = base_query.filter(
                    and_(SysDictType.create_time >= begin_date, SysDictType.create_time <= end_date))

            pa = base_query.order_by(SysDictType.create_time.desc()).paginate(page_num, page_size, False)
            rows_data = [response_camel_case_dict(item.to_dict()) for item in pa.items]
            res_dict["rows"] = rows_data
            res_dict["total"] = pa.total
        return res_dict

    def post(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        temp_object = SysDictType(**params_dict)
        save_objects([temp_object])
        return res_dict

    def put(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        dict_id = params_dict.get("dict_id")
        update_fields = [
            "dict_name",
            "dict_type",
            "status",
            "remark",
        ]
        old_object = SysDictType.query.get(dict_id)

        for item_k in update_fields:
            item_v = params_dict.get(item_k)
            if getattr(old_object, item_k) != item_v:
                setattr(old_object, item_k, item_v)
        update_objects([old_object])
        return res_dict

    def delete(self, id):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        id_list = [int(item) for item in id.split(",")]

        dict_type_list = [item.dict_type for item in SysDictType.query.filter(SysDictType.dict_id.in_(id_list)).all()]
        res_count = SysDictDatum.query.filter(SysDictDatum.dict_type.in_(dict_type_list)).count()

        if res_count > 0:
            res_dict["code"] = 500
            res_dict["msg"] = "{}存在关联数据".format(id)
            return res_dict
        SysDictType.query.filter(SysDictType.dict_id.in_(id_list)).delete()
        db.session.commit()
        return res_dict


##################岗位管理


class SysPostResource(BaseResource):

    def get(self, id=None):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        if id:
            role_dict = SysPost.query.get(id).to_dict()
            res_dict["data"] = response_camel_case_dict(role_dict)
            return res_dict
        else:
            params_dict = request.args
            params_dict = request_snake_case_dict(params_dict)
            page_num = int(params_dict.get("pageNum", 1))
            page_size = int(params_dict.get("pageSize", 10))
            base_query = SysPost.query.filter()
            post_code = params_dict.get("post_code")
            if post_code:
                base_query = base_query.filter_by(post_code=post_code)

            post_name = params_dict.get("post_name")
            if post_name:
                base_query = base_query.filter_by(post_name=post_name)
            status = params_dict.get("status")
            if status:
                base_query = base_query.filter_by(status=status)
            pa = base_query.order_by(SysPost.post_sort.asc()).paginate(page_num, page_size, False)
            rows_data = [response_camel_case_dict(item.to_dict()) for item in pa.items]
            res_dict["rows"] = rows_data
            res_dict["total"] = pa.total
        return res_dict

    def post(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        temp_object = SysPost()
        if not params_dict.get("remark"):
            params_dict["remark"] = params_dict.get("post_name")

        for item_k, item_v in params_dict.items():
            if hasattr(temp_object, item_k):
                setattr(temp_object, item_k, item_v)

        save_objects([temp_object])
        return res_dict

    def put(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        post_id = params_dict.get("post_id")
        SysPost.query.filter()

        update_fields = [
            "post_code",
            "post_name",
            "post_sort",
            "status",
            "remark",
        ]
        old_object = SysPost.query.get(post_id)
        for item_k, item_v in params_dict.items():
            if item_k in update_fields:
                if getattr(old_object, item_k) != item_v:
                    setattr(old_object, item_k, item_v)
        update_objects([old_object])
        return res_dict

    def delete(self, id):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        ids = id.split(",")
        res_count = SysUserPost.query.filter(SysUserPost.post_id.in_(ids)).count()
        if res_count > 0:
            res_dict["code"] = 500
            res_dict["msg"] = "岗位{}已分配,不能删除".format(id)
            return res_dict
        SysPost.query.filter(SysPost.post_id.in_(ids)).delete()
        db.session.commit()
        return res_dict


##################部门管理

class SysDeptExcludeResource(BaseResource):
    def get(self, id=None):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        # 排除传入的部门和其下的所有子部门
        node_ancestors = SysDept.query.get(id).ancestors
        combination_ancestors = ",".join([node_ancestors, str(id)])
        res_objects = SysDept.query.filter(not_(SysDept.ancestors.startswith(combination_ancestors))).all()
        res_rows = [response_camel_case_dict(item.to_dict()) for item in res_objects]
        res_dict["data"] = res_rows
        return res_dict


class SysDeptResource(BaseResource):
    def get(self, id=None):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        if id:
            res_object = SysDept.query.get(id)
            res_dict["data"] = response_camel_case_dict(res_object.to_dict())
            return res_dict
        else:
            params_dict = request.args
            params_dict = request_snake_case_dict(params_dict)
            base_objects = SysDept.query.filter()
            dept_name = params_dict.get("dept_name")
            if dept_name:
                base_objects = base_objects.filter_by(dept_name=dept_name)
            status = params_dict.get("status")
            if status:
                base_objects = base_objects.filter_by(status=status)
            ordered_objects = base_objects.order_by(SysDept.order_num.asc()).all()
            rows_data = [response_camel_case_dict(item.to_dict()) for item in ordered_objects]
            res_dict["data"] = rows_data
            res_dict["total"] = len(ordered_objects)
            return res_dict

    def post(self):
        params_dict = request.json
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request_snake_case_dict(params_dict)
        parent_id = params_dict.get("parent_id")
        # res = SysDept.query.with_entities(SysDept.dept_id, SysDept.ancestors).filter(
        #     SysDept.dept_id == parent_id).first()
        parent_node = SysDept.query.get(parent_id)
        params_dict["ancestors"] = ",".join([parent_node.ancestors, str(parent_node.dept_id)])
        temp_object = SysDept(**params_dict)
        save_objects([temp_object])
        return res_dict

    def put(self):
        params_dict = request.json
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        dept_id = params_dict.get("dept_id")
        parent_id = params_dict.get("parent_id")

        update_fields = [
            "parent_id",
            "ancestors",
            "dept_name",
            "order_num",
            "leader",
            "phone",
            "email",
            "status",
            "del_flag",
        ]

        old_object = SysDept.query.get(dept_id)

        # 单独更新parent_id和ancestors
        parent_node = SysDept.query.get(parent_id)
        if parent_id != old_object.parent_id:
            old_object.ancestors = ",".join([parent_node.ancestors, str(parent_id)])

        for item_k, item_v in params_dict.items():
            if item_k in update_fields:
                if getattr(old_object, item_k) != item_v:
                    setattr(old_object, item_k, item_v)

        update_objects([old_object])
        return res_dict

    def delete(self, id):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        # 有子菜单，不可以删除
        child_count = SysDept.query.filter(SysDept.parent_id == id).count()
        if child_count > 0:
            res_dict["msg"] = "{}有子部门.不能被删除".format(id)
            res_dict["code"] = 500
            return res_dict

        # 执行删除操作
        SysDept.query.filter(SysDept.dept_id == id).delete()
        db.session.commit()
        return res_dict


##################菜单管理
class SysMenuResource(BaseResource):
    def get(self, id=None):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        if id:
            res_object = SysMenu.query.get(id)
            res_dict["data"] = response_camel_case_dict(res_object.to_dict())
            return res_dict
        else:
            params_dict = request.args
            params_dict = request_snake_case_dict(params_dict)
            base_objects = SysMenu.query.filter()
            menu_name = params_dict.get("menu_name")
            if menu_name:
                base_objects = base_objects.filter(SysMenu.menu_name.like("%{}".format(menu_name)))
            status = params_dict.get("status")
            if status:
                base_objects = base_objects.filter(SysMenu.status == status)
            ordered_objects = base_objects.order_by(SysMenu.order_num.asc()).all()

            rows_data = [response_camel_case_dict(item.to_dict()) for item in ordered_objects]

            res_dict["data"] = rows_data
            res_dict["total"] = len(ordered_objects)
            return res_dict

    def post(self):
        params_dict = request.json
        # {"parentId": 0,
        #  "menuName": "测试",
        #  "icon": "build",
        #  "menuType": "M",
        #  "orderNum": 6,
        #  "isFrame": "1",
        #  "isCache": "0",
        #  "visible": "0",
        #  "status": "0",
        #  "path": "test"}

        params_dict = request_snake_case_dict(params_dict)
        res_object = SysMenu(**params_dict)
        res_object.create_by = session.get("user", {}).get("user_name")

        db.session.add(res_object)
        db.session.commit()
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        return res_dict

    def put(self):
        # {"label": "官网", "id": 4, "menuId": 4, "menuName": "官网", "parentId": 0, "orderNum": 4,
        #  "path": "http://wwwfff.top", "component": None, "isFrame": "0", "isCache": "0", "menuType": "M",
        #  "visible": "0", "status": "1", "perms": "", "icon": "guide", "createBy": "admin",
        #  "createTime": "2022-03-15 14:17:28", "updateBy": "", "updateTime": "2022-03-15 14:17:28", "remark": "官网地址"}
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        menu_id = params_dict.get("menu_id")
        update_fields = [
            "menu_name",
            "parent_id",
            "order_num",
            "path",
            "component",
            "is_frame",
            "is_cache",
            "menu_type",
            "visible",
            "status",
            "perms",
            "icon",
            "create_by",
            "update_by",
            "remark",
        ]
        old_object = SysMenu.query.get(menu_id)
        for item_k, item_v in params_dict.items():
            if item_k in update_fields:
                if getattr(old_object, item_k) != item_v:
                    setattr(old_object, item_k, item_v)
        db.session.commit()
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        return res_dict

    def delete(self, id):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        # 有子菜单，不可以删除
        child_count = SysMenu.query.filter(SysMenu.parent_id == id).count()
        if child_count > 0:
            res_dict["msg"] = "{}有子菜单.不能被删除".format(id)
            res_dict["code"] = 500
            return res_dict

        # 执行删除操作
        SysMenu.query.filter(SysMenu.menu_id == id).delete()
        db.session.commit()
        return res_dict


##################角色管理

class SysRoleCancelAll(BaseResource):
    def put(self):
        res_dict = {
            "code": 200,
            "msg": "查询成功",
        }
        params_dict = request.args
        user_ids = params_dict.get("userIds").split(",")
        role_id = params_dict.get("roleId")
        delete_objects = SysUserRole.query.filter(
            and_(SysUserRole.role_id == role_id, SysUserRole.user_id.in_(user_ids))).all()
        for item in delete_objects:
            db.session.delete(item)
        db.session.commit()
        return res_dict


class SysRoleAuthUserCancel(BaseResource):
    def put(self):
        res_dict = {
            "code": 200,
            "msg": "查询成功",
        }
        params_dict = request.json
        user_id = int(params_dict.get("userId"))
        role_id = int(params_dict.get("roleId"))
        # with_entities

        res_objects = SysUserRole.query.filter(
            and_(SysUserRole.role_id == role_id, SysUserRole.user_id == user_id)
        ).all()
        for item in res_objects:
            db.session.delete(item)
        db.session.commit()
        return res_dict


class SysRoleSelectAll(BaseResource):
    def put(self):
        res_dict = {
            "code": 200,
            "msg": "查询成功",
        }
        params_dict = request.args
        role_id = params_dict.get("roleId")
        user_ids = params_dict.get("userIds").split(",")
        target_dicts = [{"user_id": item, "role_id": role_id} for item in user_ids]
        for item in target_dicts:
            temp_object = SysUserRole(**item)
            db.session.add(temp_object)
        db.session.commit()
        return res_dict


class SysRoleUnAllocatedList(BaseResource):
    def get(self):
        res_dict = {
            "code": 200,
            "msg": "查询成功",
        }
        params_dict = request.args
        page_num = int(params_dict.get("pageNum", 1))
        page_size = int(params_dict.get("pageSize", 10))
        role_id = params_dict.get("roleId")
        phonenumber = params_dict.get("phonenumber")
        user_name = params_dict.get("userName")

        # 当前角色所关联到的用户
        user_ids = [item.user_id for item in SysUserRole.query.filter_by(role_id=role_id).all()]
        base_query = SysUser.query.filter(
            and_(SysUser.user_id.notin_(user_ids), SysUser.del_flag == "0", SysUser.status == "0"))
        if user_name:
            base_query = base_query.filter(SysUser.user_name == user_name)
        if phonenumber:
            base_query = base_query.filter(SysUser.phonenumber == phonenumber)

        pa = base_query.order_by(SysUser.create_time.asc()).paginate(page_num, page_size, False)
        rows_dict = [response_camel_case_dict(item.to_dict()) for item in pa.items]
        res_dict["rows"] = rows_dict
        res_dict["total"] = pa.total
        return res_dict


# /system/role/authUser/allocatedList?pageNum=1&pageSize=10&roleId=11

class SysRoleAllocatedList(BaseResource):
    def get(self):
        res_dict = {
            "code": 200,
            "msg": "查询成功",
        }
        params_dict = request.args
        page_num = int(params_dict.get("pageNum", 1))
        page_size = int(params_dict.get("pageSize", 10))
        role_id = params_dict.get("roleId")
        phonenumber = params_dict.get("phonenumber")
        user_name = params_dict.get("userName")

        # 当前角色所关联到的用户
        user_ids = [item.user_id for item in SysUserRole.query.filter_by(role_id=role_id).all()]
        base_query = SysUser.query.filter(and_(SysUser.user_id.in_(user_ids), SysUser.del_flag == "0"))
        if user_name:
            base_query = base_query.filter(SysUser.user_name == user_name)
        if phonenumber:
            base_query = base_query.filter(SysUser.phonenumber == phonenumber)

        pa = base_query.order_by(SysUser.create_time.asc()).paginate(page_num, page_size, False)
        rows_dict = [response_camel_case_dict(item.to_dict()) for item in pa.items]
        res_dict["rows"] = rows_dict
        res_dict["total"] = pa.total
        return res_dict


class SysRoleDataScope(BaseResource):
    def put(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        role_id = params_dict.get("roleId")
        data_scope = params_dict.get("dataScope")
        dept_ids = params_dict.get("deptIds")
        # 更新角色的数据权限
        res_object = SysRole.query.get(role_id)
        res_object.data_scope = data_scope
        db.session.commit()
        if "2" == data_scope:
            # 更新部门列表
            print("#" * 10)
            print(dept_ids)
            update_dept_by_role_id(role_id, dept_ids)
        else:
            update_dept_by_role_id(role_id, [])
        return res_dict


class SysRoleDeptTreeSelect(BaseResource):
    def get(self, id):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }

        target_role = SysRole.query.get(id)

        dept_qs = SysDept.query.filter_by(status="0")

        dept_qs_2 = dept_qs.order_by(SysDept.order_num.asc())
        dept_list = [item.to_dict() for item in dept_qs_2.all()]

        res_dict["depts"] = get_label_tree(dept_list)

        target_role_dept_ids = [item.dept_id for item in SysRoleDept.query.filter_by(role_id=target_role.role_id).all()]
        dept_qs = dept_qs.filter(SysDept.dept_id.in_(target_role_dept_ids))
        # 准备当前角色所拥有的部门数据

        role_dept_ids = []

        if target_role.dept_check_strictly:
            ancestors_list = []
            for item in dept_qs.all():
                for ele in item.ancestors.split(","):
                    ancestors_list.append(int(ele))
                ancestors_list.append(item.dept_id)
            for temp_item in ancestors_list:
                if ancestors_list.count(temp_item) < 2:
                    role_dept_ids.append(temp_item)
        else:
            role_dept_ids = [item.dept_id for item in dept_qs.all()]
        res_dict["checkedKeys"] = role_dept_ids
        return res_dict


class SysRoleMenuTreeSelect(BaseResource):
    def get(self, id):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        role_menu_ids = [item.menu_id for item in SysRoleMenu.query.filter_by(role_id=id).all()]
        menu_objects = SysMenu.query.filter_by(status="0")
        menu_objects = menu_objects.order_by(SysMenu.order_num.asc()).all()
        menu_list = [item.to_dict() for item in menu_objects]
        res_dict["checkedKeys"] = role_menu_ids
        res_dict["menus"] = get_label_tree(menu_list)
        return res_dict


class SysRoleTreeSelect(BaseResource):
    def get(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        menu_objects = SysMenu.query.filter_by(status="0") \
            .order_by(SysMenu.order_num.asc()).all()
        menu_list = [item.to_dict() for item in menu_objects]
        res_dict["data"] = get_label_tree(menu_list)
        return res_dict


class SysRoleChangeStatus(BaseResource):
    def put(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        role_id = params_dict.get("roleId")
        new_status = params_dict.get("status")
        res_object = SysRole.query.get(role_id)
        res_object.status = new_status
        db.session.commit()
        return res_dict


class SysRoleResource(BaseResource):

    def get(self, id=None):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        if id:
            print("#" * 10)
            print(id)
            role_dict = SysRole.query.get(id).to_dict()
            res_dict["data"] = response_camel_case_dict(role_dict)
            return res_dict
        else:
            params_dict = request.args
            page_num = int(params_dict.get("pageNum", 1))
            page_size = int(params_dict.get("pageSize", 10))
            status = params_dict.get("status")
            qs = SysRole.query.filter_by(del_flag="0")
            if status in ['0', '1']:
                qs = qs.filter_by(status=status)
            role_name = params_dict.get("roleName")
            if role_name:
                qs = qs.filter(SysRole.role_name.like('%' + role_name + "%"))
            role_key = params_dict.get("roleKey")
            if role_key:
                qs = qs.filter(SysRole.role_key.like("%{}%".format(role_key)))
            begin_time = params_dict.get("params[beginTime]")
            end_time = params_dict.get("params[endTime]")
            if begin_time and end_time:
                begin_date = datetime.strptime(begin_time, "%Y-%m-%d")
                end_date = datetime.strptime(end_time, "%Y-%m-%d")
                qs = qs.filter(SysRole.create_time >= begin_date).filter(SysRole.create_time <= end_date)
                # qs.filter(and_(SysRole.create_time >= begin_date, SysRole.create_time <= end_date))
            pa = qs.order_by(SysRole.role_sort.asc()).paginate(page_num, page_size, False)
            rows_data = [response_camel_case_dict(item.to_dict()) for item in pa.items]
            res_dict["rows"] = rows_data
            res_dict["total"] = pa.total
        return res_dict

    def post(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)

        count_number = SysRole.query.filter_by(role_key=params_dict.get("role_key")).count()
        if count_number > 0:
            res_dict["code"] = 500
            res_dict["msg"] = "权限字符串{}已存在".format(params_dict.get("role_key"))
            return res_dict

        sys_role_dict = {
            "role_name": params_dict.get("role_name"),
            "role_key": params_dict.get("role_key"),
            "role_sort": params_dict.get("role_sort"),
            "data_scope": params_dict.get("data_scope"),
            "menu_check_strictly": "1" if params_dict.get("menu_check_strictly") else "0",
            "dept_check_strictly": "1" if params_dict.get("dept_check_strictly") else "0",
            "remark": params_dict.get("remark"),
        }

        new_object = SysRole(**sys_role_dict)
        db.session.add(new_object)
        db.session.commit()

        new_role_id = new_object.role_id
        new_menu_ids = params_dict.get("menu_ids")
        update_menu_by_role_id(role_id=new_role_id, new_menu_ids=new_menu_ids)
        db.session.commit()
        res_dict["msg"] = str(new_role_id) + "添加成功"
        return res_dict

    def put(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        role_id = params_dict.get("role_id")
        menu_ids = params_dict.get("menu_ids")
        params_dict["menu_check_strictly"] = "1" if params_dict.get("menu_check_strictly") else "0"
        params_dict["dept_check_strictly"] = "1" if params_dict.get("dept_check_strictly") else "0"
        update_fields = [
            "role_name",
            "role_key",
            "role_sort",
            "data_scope",
            "menu_check_strictly",
            "dept_check_strictly",
            "remark",
            "status",
        ]
        old_object = SysRole.query.get(role_id)
        for item_k, item_v in params_dict.items():
            if item_k in update_fields:
                if getattr(old_object, item_k) != item_v:
                    setattr(old_object, item_k, item_v)
        db.session.commit()
        # 更新当前角色的菜单列表
        update_menu_by_role_id(role_id, menu_ids)
        return res_dict

    def delete(self, id):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        id_list = [int(item) for item in id.split(",")]
        del_objects = SysRole.query.filter(SysRole.role_id.in_(id_list))
        res = SysUserRole.query.filter(SysUserRole.role_id.in_(id_list)).all()
        if res:
            res_dict["code"] = 500
            res_dict["msg"] = id + "已分配用户,不能删除"
            return res_dict
        for item in del_objects:
            db.session.delete(item)
        del_role_menu_objects = SysRoleMenu.query.filter(SysRoleMenu.role_id.in_(id_list)).all()
        for item in del_role_menu_objects:
            db.session.delete(item)
        del_role_dept_objects = SysRoleDept.query.filter(SysRoleDept.role_id.in_(id_list)).all()
        for item in del_role_dept_objects:
            db.session.delete(item)

        db.session.commit()
        return res_dict


##################角色

class SysUserExport(BaseResource):
    def post(self):
        res_dict = {
            "code": 200,
            "msg": "导出成功",
        }
        return res_dict


class SysUserImportData(BaseResource):

    def post(self):
        res_dict = {
            "code": 200,
            "msg": "导入成功",
        }
        return res_dict


class SysUserImportTemplate(BaseResource):

    def get(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        return res_dict

    def post(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        return res_dict


class SysUserAuthRoleResource(BaseResource):
    def get(self, id):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        target_object = SysUser.query.get(id)
        # 查询到当前用户的岗位和角色
        user_roles = [
            item.role_id for item in
            SysUserRole.query.filter_by(user_id=id).all()]
        user_role_objects = SysRole.query.filter(SysRole.role_id.in_(user_roles)).all()
        user_role_dict = [response_camel_case_dict(item.to_dict()) for item in user_role_objects]
        row = response_camel_case_dict(target_object.to_dict())
        row["roles"] = user_role_dict
        res_dict["user"] = row
        temp_roles = [response_camel_case_dict(item.to_dict()) for item in SysRole.query.all()]
        # 更新选中状态
        for item in temp_roles:
            if item.get("roleId") in user_roles:
                item["flag"] = True
            else:
                item["flag"] = False

        res_dict["roles"] = temp_roles
        return res_dict

    def put(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.args
        # 更新角色信息
        user_id = params_dict.get("userId")
        role_ids = params_dict.get("roleIds").split(",")

        temp_objects = SysUserRole.query.filter_by(user_id=user_id).all()
        old_role_ids = [item.role_id for item in temp_objects]
        new_role_ids = [int(item) for item in role_ids]
        add_role_ids = list(set(new_role_ids) - set(old_role_ids))
        delete_role_ids = list(set(old_role_ids) - set(new_role_ids))
        add_objects = [SysUserRole(**{"user_id": user_id, "role_id": item}) for item in add_role_ids]
        db.session.add_all(add_objects)
        delete_objects = SysUserRole.query.filter(SysUserRole.role_id.in_(delete_role_ids)).all()
        for item in delete_objects:
            db.session.delete(item)
        db.session.commit()
        return res_dict


class SysUserResetPwdResource(BaseResource):
    def put(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
            "data": []
        }
        params_dict = request.json
        user_id = params_dict.get("userId")
        password = params_dict.get("password").encode("utf-8")
        hashed_password = bcrypt.hashpw(password, bcrypt.gensalt(10, prefix=b"2a")).decode("utf-8")
        target_object = SysUser.query.get(user_id)
        target_object.password = hashed_password
        res_dict["msg"] = "密码修改成功"
        return res_dict


class SysUserProfileUpdatePwdResource(BaseResource):
    def put(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
            "data": {}
        }

        return res_dict


class SysUserProfileResource(BaseResource):

    def get(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
            "data": {}
        }
        from flask import g
        t_user_info = g.token_info
        t_username = t_user_info.get("username")
        user_object = SysUser.query.filter_by(user_name=t_username.strip()).first()
        res_dict["data"] = response_camel_case_dict(user_object.to_dict())
        return res_dict

    def put(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
            "data": {}
        }

        return res_dict


class SysUserResource(BaseResource):
    def get(self, id=None):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
            "data": []
        }
        if id:
            target_object = SysUser.query.get(id)
            # 查询到当前用户的岗位和角色
            rolesIds = [item.role_id for item in SysUserRole.query.filter_by(user_id=id).all()]
            postIds = [item.post_id for item in SysUserPost.query.filter_by(user_id=id).all()]
            row = response_camel_case_dict(target_object.to_dict())
            res_dict["roleIds"] = rolesIds
            res_dict["postIds"] = postIds
            res_dict["data"] = row
            res_dict["roles"] = [response_camel_case_dict(item.to_dict()) for item in SysRole.query.all()]
            res_dict["posts"] = [response_camel_case_dict(item.to_dict()) for item in SysPost.query.all()]
            return res_dict
        else:
            params_dict = request.args
            page_num = int(params_dict.get("pageNum", 1))
            page_size = int(params_dict.get("pageSize", 10))
            pa = SysUser.query.filter().paginate(page_num, page_size, False)
            res_rows = [response_camel_case_dict(item.to_dict()) for item in pa.items]
            roles = []
            posts = []
            if not params_dict:
                roles = [response_camel_case_dict(item.to_dict()) for item in SysRole.query.all()]
                posts = [response_camel_case_dict(item.to_dict()) for item in SysPost.query.all()]
            return {
                "code": 200,
                "msg": "操作成功",
                "rows": res_rows,
                "total": pa.total,
                "roles": roles,
                "posts": posts
            }

    def post(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json

        post_ids = params_dict.pop("postIds")
        role_ids = params_dict.pop("roleIds")
        params_dict_new = request_snake_case_dict(params_dict)
        user_name = params_dict_new.get("user_name")
        if not user_name:
            res_dict["code"] = 0
            res_dict["msg"] = "用户名不能为空"
            return res_dict

        user = SysUser.query.filter_by(user_name=params_dict_new.get("user_name")).first()
        if user:
            res_dict["code"] = 0
            res_dict["msg"] = "用户名已存在"
            return res_dict

        # 生成加密的密码串并保存
        password = params_dict.get("password").encode("utf-8")
        hashed_password = bcrypt.hashpw(password, bcrypt.gensalt(10, prefix=b"2a")).decode("utf-8")

        temp_sys_user = SysUser(**params_dict_new)
        temp_sys_user.password = hashed_password

        db.session.add(temp_sys_user)
        db.session.commit()
        # 更新该用户的岗位和角色
        post_ids_list = [{"user_id": temp_sys_user.user_id, "post_id": item} for item in post_ids]
        role_ids_list = [{"user_id": temp_sys_user.user_id, "role_id": item} for item in role_ids]

        post_ids_objects = [SysUserPost(**obj) for obj in post_ids_list]
        role_ids_objects = [SysUserRole(**obj) for obj in role_ids_list]
        db.session.add_all(post_ids_objects)
        db.session.add_all(role_ids_objects)
        db.session.commit()

        res_dict["data"] = temp_sys_user.user_id
        return res_dict

    def put(self):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        params_dict = request.json
        params_dict = request_snake_case_dict(params_dict)
        user_id = params_dict.get("user_id")
        old_object = SysUser.query.get(user_id)
        update_fields = [
            "dept_id",
            "nick_name",
            "email",
            "phonenumber",
            "sex",
            "avatar",
            "status",
            "del_flag",
            "remark"
        ]
        for item_k, item_v in params_dict.items():
            if item_k in update_fields:
                if getattr(old_object, item_k) != item_v:
                    setattr(old_object, item_k, item_v)
        db.session.add(old_object)
        # db.session.commit()
        # 更新岗位和角色
        new_post_ids = params_dict.pop("post_ids")
        old_post_ids = [item.post_id for item in SysUserPost.query.filter_by(user_id=user_id).all()]
        add_post_ids = list(set(new_post_ids) - set(old_post_ids))
        post_ids_list = [{"user_id": user_id, "post_id": item} for item in add_post_ids]
        post_ids_objects = [SysUserPost(**obj) for obj in post_ids_list]
        db.session.add_all(post_ids_objects)
        # db.session.commit()
        delete_post_ids = list(set(old_post_ids) - set(new_post_ids))
        delete_objects = SysUserPost.query.filter(SysUserPost.post_id.in_(delete_post_ids)).all()
        for item in delete_objects:
            db.session.delete(item)
        # db.session.commit()
        new_role_ids = params_dict.pop("role_ids")
        old_role_ids = [item.role_id for item in SysUserRole.query.filter_by(user_id=user_id).all()]
        add_role_ids = list(set(new_role_ids) - set(old_role_ids))
        add_role_ids_list = [{"user_id": user_id, "role_id": item} for item in add_role_ids]
        add_role_ids_objects = [SysUserRole(**obj) for obj in add_role_ids_list]
        db.session.add_all(add_role_ids_objects)
        delete_role_ids = list(set(old_role_ids) - set(new_role_ids))
        delete_objects = SysUserRole.query.filter(SysUserRole.role_id.in_(delete_role_ids))
        for item in delete_objects:
            db.session.delete(item)
        db.session.commit()
        res_dict["data"] = old_object.user_id
        return res_dict

    def delete(self, id):
        res_dict = {
            "code": 200,
            "msg": "操作成功",
        }
        delete_object = SysUser.query.get(id)
        delete_object_roles = SysUserRole.query.filter_by(user_id=id).all()
        delete_object_posts = SysUserPost.query.filter_by(user_id=id).all()
        db.session.delete(delete_object)
        for item in delete_object_roles:
            db.session.delete(item)
        for item in delete_object_posts:
            db.session.delete(item)
        db.session.commit()
        res_dict["id"] = id
        return res_dict


class SysUserChangeStatusResource(BaseResource):
    def put(self):
        params_dict = request.json
        target_sys_user = SysUser.query.filter_by(user_id=params_dict.get("userId")).first()
        target_sys_user.status = params_dict.get("status")
        db.session.commit()
        return {
            "data": target_sys_user.to_dict()
        }


class TreeSelectResource(BaseResource):

    def get(self):
        sys_dept_list = [item.to_dict() for item in SysDept.query.all()]
        return {
            "code": 200,
            "msg": "操作成功",
            "data": get_label_tree(sys_dept_list)
        }


class DataTypeResource(BaseResource):

    def get(self, dict_type):
        dict_type = dict_type.strip()
        res_dict_data_objects = SysDictDatum.query.filter(SysDictDatum.dict_type == dict_type).filter_by(
            status="0").all()
        res_sys_dict_type_list = [response_camel_case_dict(item.to_dict()) for item in res_dict_data_objects]
        return {
            "code": 200,
            "msg": "操作成功",
            "data": res_sys_dict_type_list
        }


class LoginOutResource(BaseResource):
    def post(self):
        res_dict = {
            "code": 200,
            "msg": "success",
        }

        return res_dict


class CaptchaImageResource(Resource):

    def get(self):
        res_dict = {"msg": "操作成功",
                    "img": "",
                    "code": 200, "captchaOnOff": False, "uuid": ""}
        return res_dict


class GetRoutersResource(BaseResource):

    def get(self):
        res_dict = {"msg": "操作成功",
                    "code": 200,
                    "data": []}
        param_user_name = "admin"
        # 获取用户的角色
        sys_user_object = SysUser.query.filter_by(user_name=param_user_name).first()
        current_user_role_ids = [item.role_id for item in SysUserRole.query.filter_by(user_id=sys_user_object.user_id)]
        # 获取到角色所有的菜单

        sys_menu_objects = SysMenu.query.filter_by(status="0")
        if 1 not in current_user_role_ids:
            sys_menu_ids = [item.menu_id for item in
                            SysRoleMenu.query.filter(SysRoleMenu.role_id.in_(current_user_role_ids)).all()]
            sys_menu_objects = sys_menu_objects.filter(SysMenu.menu_id.in_(sys_menu_ids))
        else:
            pass
        sys_menu_list = [item.to_dict() for item in sys_menu_objects.all()]
        sys_menu_list_top = []
        for item in sys_menu_list:
            if item.get("parent_id") == 0:
                sys_menu_list_top.append(item)
        res_dict["data"] = gen_routers(sys_menu_list_top, sys_menu_list)
        return res_dict


class GetInfoResource(BaseResource):
    def get(self):
        res_dict = {"msg": "操作成功",
                    "code": 200,
                    "permissions": [],
                    "roles": ["test"],
                    }

        sys_user = SysUser.query.filter_by(user_name="admin").first()
        sys_user_role = SysUserRole.query.filter_by(user_id=sys_user.user_id).all()
        current_user_roles = [item.role_id for item in sys_user_role]
        if 1 in current_user_roles:
            res_dict["permissions"] = [item.perms for item in SysMenu.query.all()]
        else:
            sys_role_menu = SysRoleMenu.query.filter(SysRoleMenu.role_id.in_(current_user_roles)).all()
            current_role_menu_ids = [item.menu_id for item in sys_role_menu]
            res_dict["permissions"] = [item.perms for item in
                                       SysMenu.query.filter(SysMenu.menu_id.in_(current_role_menu_ids)).all()]
            res_dict["admin"] = False

        sys_roles = SysRole.query.filter(SysRole.role_id.in_(current_user_roles)).all()
        res_dict["roles"] = [item.role_key for item in sys_roles]
        res_dict["roleIds"] = [item.role_id for item in sys_roles]
        sys_user_dict = response_camel_case_dict(sys_user.to_dict())
        sys_user_dict["roles"] = [response_camel_case_dict(item.to_dict()) for item in sys_roles]
        res_dict["user"] = sys_user_dict
        return res_dict


class LoginResource(Resource):
    def post(self):
        res_dict = {
            "code": 200,
            "msg": "success",
            "token": ""
        }
        if not request.is_json:
            return {"msg": "Missing JSON in request"}

        username = request.json.get("username", None)
        password = request.json.get("password", None)
        user = SysUser.query.filter_by(user_name=username).first()
        if user:
            encryption_password = user.password
            if bcrypt.checkpw(password.encode("utf-8"), encryption_password.encode("utf-8")):
                token = get_token(username)
                res_dict["token"] = token
                return res_dict
            else:
                res_dict["code"] = 500
                res_dict["msg"] = "密码不对"
                return res_dict
        else:
            res_dict["code"] = 500
            res_dict["msg"] = "用户不存在"
            return res_dict


class RegisterResource(Resource):
    def post(self):
        res_dict = {
            "code": 200,
            "msg": "success",
        }
        return res_dict
